package com.xuecheng.gateway.filter;

import com.xuecheng.common.util.StringUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthGateWayFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //获取请求头数据
        HttpHeaders headers = request.getHeaders();
        List<String> authorization = headers.get("Authorization");

        if (CollectionUtils.isEmpty(authorization)) {
            return chain.filter(exchange);
            /*response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();*/
        }
        //获取token
        String jsonToken = authorization.get(0);
        //判断token是否是需要的数据
        if (StringUtil.isEmpty(jsonToken) || !jsonToken.startsWith("Bearer ")) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //把解析好的数据放到请求头中
        jsonToken = jsonToken.substring(7);
        request.mutate().header("jsonToken", jsonToken).build();
        return chain.filter(exchange);
    }
}
